<template>
  <div class="order-management">
    <!-- 顶部搜索和筛选 -->
    <div class="action-bar">
      <div class="search-box">
        <input 
          type="text" 
          v-model="searchQuery" 
          placeholder="搜索订单号/客户名称"
          @input="handleSearch"
        >
        <i class="fas fa-search"></i>
      </div>
      <div class="filters">
        <select v-model="statusFilter">
          <option value="">全部状态</option>
          <option value="pending">待付款</option>
          <option value="paid">已付款</option>
          <option value="shipped">已发货</option>
          <option value="delivered">已送达</option>
          <option value="cancelled">已取消</option>
        </select>
        <div class="date-range">
          <input 
            type="date" 
            v-model="dateRange.start"
            :max="dateRange.end"
          >
          <span>至</span>
          <input 
            type="date" 
            v-model="dateRange.end"
            :min="dateRange.start"
          >
        </div>
      </div>
      <button class="export-btn" @click="exportOrders">
        <i class="fas fa-download"></i>
        导出订单
      </button>
    </div>

    <!-- 订单列表 -->
    <div class="order-table">
      <table>
        <thead>
          <tr>
            <th>订单号</th>
            <th>客户信息</th>
            <th>商品信息</th>
            <th>订单金额</th>
            <th>支付方式</th>
            <th>订单状态</th>
            <th>下单时间</th>
            <th>操作</th>
          </tr>
        </thead>
        <tbody>
          <tr v-for="order in filteredOrders" :key="order._id">
            <td>{{ order._id }}</td>
            <td>
              <div class="customer-info">
                <div>{{ order.user.username }}</div>
                <div class="text-small">{{ order.shippingAddress.phone }}</div>
              </div>
            </td>
            <td>
              <div class="order-items">
                <div v-for="item in order.items" :key="item.product._id">
                  {{ item.product.name }} × {{ item.quantity }}
                </div>
              </div>
            </td>
            <td>¥{{ order.totalAmount }}</td>
            <td>{{ order.paymentMethod }}</td>
            <td>
              <span class="status-tag" :class="order.status">
                {{ getStatusText(order.status) }}
              </span>
            </td>
            <td>{{ formatDate(order.createdAt) }}</td>
            <td>
              <div class="action-buttons">
                <button class="view-btn" @click="viewOrderDetail(order)">
                  <i class="fas fa-eye"></i>
                </button>
                <button 
                  v-if="order.status === 'paid'"
                  class="ship-btn" 
                  @click="handleShip(order)"
                >
                  <i class="fas fa-truck"></i>
                </button>
                <button 
                  v-if="order.status === 'pending'"
                  class="cancel-btn" 
                  @click="handleCancel(order)"
                >
                  <i class="fas fa-times"></i>
                </button>
              </div>
            </td>
          </tr>
        </tbody>
      </table>
    </div>

    <!-- 分页 -->
    <div class="pagination">
      <button 
        :disabled="currentPage === 1"
        @click="currentPage--"
      >
        <i class="fas fa-chevron-left"></i>
      </button>
      <span>第 {{ currentPage }} 页</span>
      <button 
        :disabled="currentPage === totalPages"
        @click="currentPage++"
      >
        <i class="fas fa-chevron-right"></i>
      </button>
    </div>

    <!-- 订单详情弹窗 -->
    <div class="modal" v-if="showDetailModal">
      <div class="modal-content">
        <div class="modal-header">
          <h3>订单详情</h3>
          <button class="close-btn" @click="showDetailModal = false">
            <i class="fas fa-times"></i>
          </button>
        </div>
        <div class="modal-body" v-if="selectedOrder">
          <div class="detail-section">
            <h4>基本信息</h4>
            <div class="detail-row">
              <span class="label">订单号：</span>
              <span>{{ selectedOrder._id }}</span>
            </div>
            <div class="detail-row">
              <span class="label">下单时间：</span>
              <span>{{ formatDate(selectedOrder.createdAt) }}</span>
            </div>
            <div class="detail-row">
              <span class="label">订单状态：</span>
              <span class="status-tag" :class="selectedOrder.status">
                {{ getStatusText(selectedOrder.status) }}
              </span>
            </div>
          </div>

          <div class="detail-section">
            <h4>客户信息</h4>
            <div class="detail-row">
              <span class="label">客户名称：</span>
              <span>{{ selectedOrder.user.username }}</span>
            </div>
            <div class="detail-row">
              <span class="label">联系电话：</span>
              <span>{{ selectedOrder.shippingAddress.phone }}</span>
            </div>
            <div class="detail-row">
              <span class="label">收货地址：</span>
              <span>{{ formatAddress(selectedOrder.shippingAddress) }}</span>
            </div>
          </div>

          <div class="detail-section">
            <h4>商品信息</h4>
            <div class="order-items-table">
              <table>
                <thead>
                  <tr>
                    <th>商品名称</th>
                    <th>单价</th>
                    <th>数量</th>
                    <th>小计</th>
                  </tr>
                </thead>
                <tbody>
                  <tr v-for="item in selectedOrder.items" :key="item.product._id">
                    <td>{{ item.product.name }}</td>
                    <td>¥{{ item.price }}</td>
                    <td>{{ item.quantity }}</td>
                    <td>¥{{ item.price * item.quantity }}</td>
                  </tr>
                </tbody>
              </table>
            </div>
            <div class="order-total">
              <div class="total-row">
                <span>商品总额：</span>
                <span>¥{{ selectedOrder.totalAmount }}</span>
              </div>
              <div class="total-row" v-if="selectedOrder.discount">
                <span>优惠金额：</span>
                <span>-¥{{ selectedOrder.discount }}</span>
              </div>
              <div class="total-row">
                <span>实付金额：</span>
                <span class="final-price">¥{{ selectedOrder.totalAmount - (selectedOrder.discount || 0) }}</span>
              </div>
            </div>
          </div>

          <div class="detail-section">
            <h4>支付信息</h4>
            <div class="detail-row">
              <span class="label">支付方式：</span>
              <span>{{ selectedOrder.paymentMethod }}</span>
            </div>
            <div class="detail-row">
              <span class="label">支付状态：</span>
              <span>{{ selectedOrder.paymentStatus }}</span>
            </div>
            <div class="detail-row" v-if="selectedOrder.paymentTime">
              <span class="label">支付时间：</span>
              <span>{{ formatDate(selectedOrder.paymentTime) }}</span>
            </div>
          </div>
        </div>
      </div>
    </div>

    <!-- 发货弹窗 -->
    <div class="modal" v-if="showShipModal">
      <div class="modal-content">
        <div class="modal-header">
          <h3>订单发货</h3>
          <button class="close-btn" @click="showShipModal = false">
            <i class="fas fa-times"></i>
          </button>
        </div>
        <div class="modal-body">
          <form @submit.prevent="confirmShip">
            <div class="form-group">
              <label>物流公司</label>
              <select v-model="shipForm.carrier" required>
                <option value="sf">顺丰速运</option>
                <option value="zt">中通快递</option>
                <option value="yd">韵达快递</option>
                <option value="ems">EMS</option>
              </select>
            </div>
            <div class="form-group">
              <label>运单号</label>
              <input type="text" v-model="shipForm.trackingNumber" required>
            </div>
            <div class="form-group">
              <label>备注</label>
              <textarea v-model="shipForm.remark" rows="3"></textarea>
            </div>
            <div class="form-actions">
              <button type="button" class="cancel-btn" @click="showShipModal = false">取消</button>
              <button type="submit" class="submit-btn">确认发货</button>
            </div>
          </form>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, computed } from 'vue'
import { orderApi } from '@/api'
import type { Order } from '@/types'

// 状态变量
const orders = ref<Order[]>([])
const searchQuery = ref('')
const statusFilter = ref('')
const currentPage = ref(1)
const totalPages = ref(1)
const showDetailModal = ref(false)
const showShipModal = ref(false)
const selectedOrder = ref<Order | null>(null)
const dateRange = ref({
  start: '',
  end: new Date().toISOString().split('T')[0]
})

// 发货表单
const shipForm = ref({
  carrier: '',
  trackingNumber: '',
  remark: ''
})

// 过滤订单列表
const filteredOrders = computed(() => {
  return orders.value.filter(order => {
    const matchQuery = order._id.toLowerCase().includes(searchQuery.value.toLowerCase()) ||
                      order.user.username.toLowerCase().includes(searchQuery.value.toLowerCase())
    const matchStatus = !statusFilter.value || order.status === statusFilter.value
    const orderDate = new Date(order.createdAt)
    const matchDate = (!dateRange.value.start || orderDate >= new Date(dateRange.value.start)) &&
                     (!dateRange.value.end || orderDate <= new Date(dateRange.value.end))
    return matchQuery && matchStatus && matchDate
  })
})

// 获取状态文本
const getStatusText = (status: string) => {
  const statusMap: Record<string, string> = {
    pending: '待付款',
    paid: '已付款',
    shipped: '已发货',
    delivered: '已送达',
    cancelled: '已取消'
  }
  return statusMap[status] || status
}

// 格式化日期
const formatDate = (date: string) => {
  return new Date(date).toLocaleString('zh-CN')
}

// 格式化地址
const formatAddress = (address: any) => {
  return `${address.city}${address.address} (${address.name} ${address.phone})`
}

// 搜索处理
const handleSearch = () => {
  currentPage.value = 1
  fetchOrders()
}

// 查看订单详情
const viewOrderDetail = (order: Order) => {
  selectedOrder.value = order
  showDetailModal.value = true
}

// 发货处理
const handleShip = (order: Order) => {
  selectedOrder.value = order
  showShipModal.value = true
}

// 确认发货
const confirmShip = async () => {
  if (!selectedOrder.value) return

  try {
    await orderApi.updateStatus(selectedOrder.value._id, 'shipped')
    await orderApi.update(selectedOrder.value._id, {
      delivery: shipForm.value
    })
    
    const index = orders.value.findIndex(o => o._id === selectedOrder.value?._id)
    if (index !== -1) {
      orders.value[index].status = 'shipped'
    }
    
    showShipModal.value = false
    shipForm.value = {
      carrier: '',
      trackingNumber: '',
      remark: ''
    }
  } catch (error) {
    console.error('Failed to ship order:', error)
  }
}

// 取消订单
const handleCancel = async (order: Order) => {
  if (!confirm(`确定要取消订单 ${order._id} 吗？`)) return

  try {
    await orderApi.updateStatus(order._id, 'cancelled')
    const index = orders.value.findIndex(o => o._id === order._id)
    if (index !== -1) {
      orders.value[index].status = 'cancelled'
    }
  } catch (error) {
    console.error('Failed to cancel order:', error)
  }
}

// 导出订单
const exportOrders = () => {
  // 实现导出逻辑
}

// 获取订单列表
const fetchOrders = async () => {
  try {
    const response = await orderApi.getList({
      page: currentPage.value,
      status: statusFilter.value,
      startDate: dateRange.value.start,
      endDate: dateRange.value.end
    })
    orders.value = response.data
    totalPages.value = Math.ceil(response.total / response.pageSize)
  } catch (error) {
    console.error('Failed to fetch orders:', error)
  }
}

// 初始化
fetchOrders()
</script>

<style scoped>
.order-management {
  padding: 24px;
}

.action-bar {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 24px;
}

.search-box {
  position: relative;
  width: 300px;
}

.search-box input {
  width: 100%;
  padding: 8px 32px 8px 12px;
  border: 1px solid #d9d9d9;
  border-radius: 4px;
}

.search-box i {
  position: absolute;
  right: 12px;
  top: 50%;
  transform: translateY(-50%);
  color: #999;
}

.filters {
  display: flex;
  gap: 16px;
  align-items: center;
}

.filters select {
  padding: 8px;
  border: 1px solid #d9d9d9;
  border-radius: 4px;
}

.date-range {
  display: flex;
  align-items: center;
  gap: 8px;
}

.date-range input {
  padding: 8px;
  border: 1px solid #d9d9d9;
  border-radius: 4px;
}

.export-btn {
  padding: 8px 16px;
  background-color: #52c41a;
  color: white;
  border: none;
  border-radius: 4px;
  cursor: pointer;
  display: flex;
  align-items: center;
  gap: 8px;
}

.order-table {
  background: white;
  border-radius: 8px;
  overflow: hidden;
  box-shadow: 0 1px 2px rgba(0, 0, 0, 0.06);
}

table {
  width: 100%;
  border-collapse: collapse;
}

th, td {
  padding: 12px;
  text-align: left;
  border-bottom: 1px solid #f0f0f0;
}

th {
  background: #fafafa;
  font-weight: 500;
  color: #666;
}

.customer-info {
  display: flex;
  flex-direction: column;
  gap: 4px;
}

.text-small {
  font-size: 12px;
  color: #999;
}

.order-items {
  display: flex;
  flex-direction: column;
  gap: 4px;
  font-size: 14px;
}

.status-tag {
  padding: 2px 8px;
  border-radius: 10px;
  font-size: 12px;
}

.status-tag.pending {
  background: #fff7e6;
  color: #faad14;
}

.status-tag.paid {
  background: #f6ffed;
  color: #52c41a;
}

.status-tag.shipped {
  background: #e6f7ff;
  color: #1890ff;
}

.status-tag.delivered {
  background: #f9f0ff;
  color: #722ed1;
}

.status-tag.cancelled {
  background: #fff1f0;
  color: #ff4d4f;
}

.action-buttons {
  display: flex;
  gap: 8px;
}

.action-buttons button {
  padding: 4px 8px;
  border: none;
  border-radius: 4px;
  cursor: pointer;
}

.view-btn {
  background: #e6f7ff;
  color: #1890ff;
}

.ship-btn {
  background: #f6ffed;
  color: #52c41a;
}

.cancel-btn {
  background: #fff1f0;
  color: #ff4d4f;
}

.pagination {
  margin-top: 24px;
  display: flex;
  justify-content: center;
  align-items: center;
  gap: 16px;
}

.pagination button {
  padding: 4px 8px;
  border: 1px solid #d9d9d9;
  border-radius: 4px;
  background: white;
  cursor: pointer;
}

.pagination button:disabled {
  background: #f5f5f5;
  cursor: not-allowed;
}

.modal {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: rgba(0, 0, 0, 0.5);
  display: flex;
  align-items: center;
  justify-content: center;
  z-index: 1000;
}

.modal-content {
  background: white;
  border-radius: 8px;
  width: 800px;
  max-width: 90%;
  max-height: 90vh;
  overflow-y: auto;
}

.modal-header {
  padding: 16px 24px;
  border-bottom: 1px solid #f0f0f0;
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.modal-header h3 {
  margin: 0;
}

.close-btn {
  border: none;
  background: none;
  font-size: 18px;
  cursor: pointer;
  color: #999;
}

.modal-body {
  padding: 24px;
}

.detail-section {
  margin-bottom: 24px;
}

.detail-section h4 {
  margin: 0 0 16px 0;
  color: #333;
}

.detail-row {
  display: flex;
  margin-bottom: 8px;
}

.detail-row .label {
  width: 100px;
  color: #666;
}

.order-items-table {
  margin: 16px 0;
}

.order-total {
  margin-top: 16px;
  border-top: 1px solid #f0f0f0;
  padding-top: 16px;
}

.total-row {
  display: flex;
  justify-content: space-between;
  margin-bottom: 8px;
}

.final-price {
  color: #ff4d4f;
  font-size: 18px;
  font-weight: bold;
}

.form-group {
  margin-bottom: 16px;
}

.form-group label {
  display: block;
  margin-bottom: 8px;
  color: #666;
}

.form-group input,
.form-group select,
.form-group textarea {
  width: 100%;
  padding: 8px;
  border: 1px solid #d9d9d9;
  border-radius: 4px;
}

.form-actions {
  display: flex;
  justify-content: flex-end;
  gap: 16px;
  margin-top: 24px;
}

.submit-btn {
  padding: 8px 16px;
  background: #1890ff;
  color: white;
  border: none;
  border-radius: 4px;
  cursor: pointer;
}

.cancel-btn {
  padding: 8px 16px;
  border: 1px solid #d9d9d9;
  border-radius: 4px;
  background: white;
  cursor: pointer;
}
</style> 